import React from 'react';
import {connect} from 'dva';
import PropTypes from 'prop-types';
import reqwest from 'reqwest';
import {Link} from 'dva/router'
import {AutoComplete, Button,Row,Col,Icon,Layout,Input,Form,Breadcrumb,Select,Affix,message,notification,Modal,Spin} from 'antd';
import style from '../../styles/ResetInput.less';
import inStyle from '../../styles/Info.less';
import {numvail,selectvail} from '../../utils/Validator.js'
const phoneReg =/^1[34578]\d{9}$/g;
const FormItem = Form.Item;
const Option =Select.Option;
const AutoOption = AutoComplete.Option;
class EditStore extends React.Component{
	constructor(props){
		super(props)
		this.state={
			result:[],
			disabled:false,
			// channels:JSON.parse(sessionStorage['regions']),
			loading:false,
			visible:false,
			spinning:false,
			pressEnter:undefined
		}
	}
	openNotification(){
	  const key = `open${Date.now()}`;
	  const btnClick = function () {
	    // to hide notification box
	    notification.close(key);
	  };
	  notification.open({
	    message: '操作提示',
	    description: '在当前页面新建渠道中填写你所需要的渠道,按下回车即可完成创建新的渠道',
	    key,
	    // onClose: close,
	  });
	}
	getServer(){
		let _this = this;
		reqwest({
      url: window.host+'/api/pres',
      method: 'get',
      crossOrigin: true,
	    // headers:AUTH_KEY,
  	  // contentType: 'application/json',
  	  data:{
  	  	access_token:window.localStorage['token']
  	  },
      type: 'json',
    }).then((data) => {
    	console.log(data);
    	if(data.regions.length<1){
    		_this.openNotification()
    	}
    	this.setState({channels:data.regions})
    }).fail( (err, msg) =>{
       console.log(1)
       // this.setState({loading:true});
    })
	}
	AddRegions(e,region){
		e.preventDefault();
		let _channels = this.state.channels
		let _this = this;
		let value = e.target.value;
		console.log(this.state.pressEnter)
		// return
		if(this.state.pressEnter==undefined){
			message.error('请填写渠道')
			return
		}
		this.setState({spinning:true})
		reqwest({
      url: window.host+'/api/stores/add_region',
      method: 'post',
      crossOrigin: true,
      data: {
        access_token:localStorage['token'],
        region_name:_this.state.pressEnter,
      },
      type: 'json',
    }).then((data) => {
      console.log(data);
      if(data.status=="success"){
      	_channels.push(data.data)
      	_this.setState({channels:_channels,new_region:data.data.id+'',});
      	window.sessionStorage['regions']=JSON.stringify(_channels);
      	message.success('新建渠道成功', 0.5,()=>{ 
      		this.setState({spinning:false})
   		  })
      }else{
      	message.warning(data.msg,1)
      	this.setState({spinning:false})
      }
    }).fail( (err, msg) =>{
    	message.error('服务器连接失败',0.5)
    	this.setState({spinning:false})
      console.log(1)
    })
	}
  patchserver(params = {}) {
  	this.setState({loading:true});
    console.log('params:', params);
    let _data=[];
    let _this =this;
    reqwest({
      url: window.host+'/api/stores/update_me',
      method: 'post',
      crossOrigin: true,
      data: {
        access_token:localStorage['token'],
        region:{name:params.channel.name},
        store:{name:params.store.name,region_id:params.store.channel,contact:params.store.contact,phone:params.store.phone,address:params.store.address},
        id:_this.props.location.query.uid,
      },
      type: 'json',
    }).then((data) => {
      console.log(data);
      if(data.status=="success"){
      	message.success('更新成功', 0.5,()=>{
     		  window.location.hash='/app/stores?current='+_this.props.location.query.current;
   		  })
      }else{
      	this.setState({loading:false});
      	message.warning(data.msg,1)
      }
    }).fail( (err, msg) =>{
    	this.setState({loading:false});
    	message.error('服务器连接失败',0.5)
       console.log(1)
    })
  }
	handleSubmit(e){
    // console.log(e)
    e.preventDefault();
    let _this=this;
    this.props.form.validateFields((err, values) => {
        // console.log(this.state.payMethods.match(/\d+/g));
        let chaname= values.chaname!==undefined?values.chaname.match(/\d+/g)[0]:null;
      if (!err && (values.storename!=undefined) ) {
        console.log('Received values of form: ', values);
					_this.patchserver({
	      	 	channel:{name:values.resetcha},
	      	 	store:{name:values.storename,channel:chaname,contact:values.cantact,phone:values.iphone,address:values.address},
	      	})
      }
    });
	}
	componentWillMount(){
		this.getServer();
		this.setState({new_region:this.props.location.query.region_id})
	}
	handleChange(e){
		if(e.target.value!=''){
			// this.setState({disabled:true});j
		}else{
			// this.setState({disabled:false});
		}
	}
	render(){
		const {result,channels,disabled} =this.state;
		const formItemLayout = {
      labelCol: { span: 7},
      wrapperCol: { span: 17 },
      style:{minWidth:200}
    };
    let _math=0;
    const emailChildren = result.map((email) => {
      return <AutoOption key={email}>{email}</AutoOption>;
    });
		let _channels=null;
    if(channels!=undefined){
	     _channels = channels.map((data) =>{
	    	_math++;
	    	// console.log(data.id)
	    	return <Option value={''+data.id} key={'a'+data.id}>{data.name}</Option>
	    })
		}else{
			 _channels = <Option key='ads' value='data'>data</Option>
		}
		const {getFieldDecorator}=this.props.form;
		return(
			<Layout >
				<Layout.Content className={`${style.berad}`} >
					<Row>
						<Breadcrumb  className={`${style.blue_dia_none}`}>
							<Breadcrumb.Item ><span className={`${style.blue_dia}`}></span></Breadcrumb.Item>
              <Breadcrumb.Item className={`${style.bread_div} ${style.bread_div_first}`}><Link to={{pathname:'/app/stores',query:{current:this.props.location.query.current}}}>门店</Link></Breadcrumb.Item>
              <Breadcrumb.Item className={`${style.bread_div}`}>编辑门店</Breadcrumb.Item>
	       		</Breadcrumb>
	       	</Row>
				</Layout.Content>
				<Layout style={{background:'#fff'}}>
				<Form className={`${inStyle.ncc_left_layout}`} onSubmit={this.handleSubmit.bind(this)}>
					<Row style={{marginTop:26}}>
						<Col className={`${style.reset_col}`} sm={{span :8,pull:0}} xs={{span:24,pull:3}}>
							<FormItem  {...formItemLayout} label='门店'>
								{getFieldDecorator('storename',{
									initialValue:this.props.location.query.name,
									rules:[{required:true,message:'请输入门店'}]
								})(
									<Input className={`${style.ncc_reset_input}`} placeholder='门店' />
								)}
							</FormItem>
						</Col>
					</Row>	
					<Row >					
						<Col sm={{span :8,pull:0,}} className={`${style.reset_col}`} xs={{span:24,pull:3}}>
							<FormItem  {...formItemLayout} label='联系人'>
								{getFieldDecorator('cantact',{
									initialValue:this.props.location.query.contact,
									rules:[{required:true,message:'请输入联系人'}],
								})(
									<Input className={`${style.ncc_reset_input}`} placeholder='联系人' />
								)}
							</FormItem>
						</Col>
					</Row>	
					<Row >
						<Col className={`${style.reset_col}`} sm={{span :8,pull:0}} xs={{span:24,pull:3}}>
							<FormItem {...formItemLayout} label='手机号码' >
								{getFieldDecorator('iphone',{
									initialValue:this.props.location.query.mobile,

									rules:[{required:true,message:'请输入手机号码',len:11,type:'string',pattern:phoneReg,validator:(rule,value,callback)=>{
										numvail(rule,value,callback)
									}}]
								})(
									<Input className={`${style.ncc_reset_input}`} placeholder='手机号码' />
								)}
							</FormItem>
						</Col>
					</Row>	
					<Row >
						<Col sm={{span :8,pull:0,}} className={`${style.reset_col}`} xs={{span:24,pull:3}}>
							<FormItem  {...formItemLayout} label='地址'>
								{getFieldDecorator('address',{
									initialValue:this.props.location.query.address,
									rules:[{required:true,message:'请输入地址'}]
								})(
									<Input className={`${style.ncc_reset_input}`} placeholder='地址' />
								)}
							</FormItem>
						</Col>
					</Row>
					<Row>
						<Breadcrumb style={{ height:60,lineHeight:'60px',fontSize:14}}>
	              <Breadcrumb.Item>渠道</Breadcrumb.Item>
	       		</Breadcrumb>
       		</Row>
       		<Row>
       			<Col className={`${style.reset_col}`} sm={{span :8,pull:0}} xs={{span:24,pull:3}} >
							<FormItem  {...formItemLayout} label='选择渠道'>
								{getFieldDecorator('chaname',{
									initialValue:this.state.new_region,
								})(
									<Select disabled={disabled}  className={`${style.ncc_reset_border}`} onChange={(e)=>{this.setState({payMethods:e})}} placeholder="所属渠道" optionFilterProp='children' showSearch>
										{_channels}
									</Select>
								)}
							</FormItem>
						</Col>
					</Row>	
					<Row >
						<Col sm={{span :8,pull:0,}} className={`${style.reset_col}`} xs={{span:24,pull:3}}>
							<FormItem help='点击保存即可新建渠道' {...formItemLayout} label='新建渠道'>
								{getFieldDecorator('resetcha',{
									initialValue:undefined,
								})(
									<Input style={{borderRadius:4}} addonAfter={<Spin size='small' style={{marginLeft:'-39px'}} spinning={this.state.spinning}> <a style={{marginLeft:'-39px',display:'inline-block',height:32,lineHeight:'28px'}} onClick={(e)=>{this.AddRegions(e)}}>保存</a> </Spin>}  onChange={(e)=>this.setState({pressEnter:e.target.value})} className={`${style.ncc_reset_input}`} placeholder='新建渠道' />
								)}
							</FormItem>
						</Col>
       		</Row>
        		
       		<Row>
	       		<Col xl={{offset:3}} lg={{offset:2}} sm={{span :8,pull:0}} xs={{span:17,pull:3}}  >
		       		<div  style={{float:'left'}} >
		       			<FormItem >
			            <Button loading={this.state.loading} htmlType="submit" size='large' type="primary"  >
			              保存
			            </Button>
		          	</FormItem>
		          </div>
		          <div  style={{float:'left',marginLeft:10}} >
		          	<Button size='large'  >
			              <Link to={{pathname:'/app/stores',query:{current:this.props.location.query.current}}}>取消</Link>
			          </Button>
		          </div>
	          </Col>
          </Row>
				</Form>	
				<Modal title='新建渠道' visible={this.state.visible} onCancel={()=>{this.setState({visible:false})}} onOk={(e,value)=>{this.AddRegions(e,value)}}  >
					<Input  onChange={(e)=>this.setState({pressEnter:e.target.value})} className={`${style.ncc_reset_input}`} placeholder='新建渠道' />
				</Modal>
				</Layout>		
			</Layout>
		)
	}
}
 
// <Row  >
						// <Breadcrumb style={{ height:60,lineHeight:'60px',fontSize:14}}>
	     //          <Breadcrumb.Item>备注<span style={{fontSize:12}}>(选填项)</span></Breadcrumb.Item>
	     //   		</Breadcrumb>
      //  		</Row>
      //  		<Row >
      //  			<Col className={`${style.reset_col}`} sm={{span :17,pull:0}} xs={{span:17,pull:0}}>
						// 	<FormItem  >
						// 	{getFieldDecorator('remark',{
						// 	})(
						// 		<Input autosize={true} type='textarea' className={`${style.ncc_reset_input} `} placeholder='备注:' />
						// 	)}
						// </FormItem>
						// </Col>
      //  		</Row>
const EditStoreForm = Form.create()(EditStore);

export default connect()(EditStoreForm)
